import {
  getNumber,
  getRouter,
  getPASSWORD_KEY,
  getUSERNAME_KEY
} from '../../utils/auth'
import {
  getPermissionsByUserId,
  login
} from '@/api'

import store from '../../store'

import {
  constantRoutes
} from '../../router'
import {
  views
} from '../../router/modules/dynamicRoutes'
import Layout from '@/layout/layout'

const state = {
  routes: [], //用户选择显示的路由
  addRoutes: [],
  userRouter: [] //用户默认所有的路由
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_USSER_ROUTES: (state, routes) => {
    state.userRouter = routes
    const rou = JSON.parse(localStorage.getItem('routes'))
    if (rou) {
      state.addRoutes = rou
      state.routes = constantRoutes.concat(rou)
    } else {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  }
}



const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise((resolve, reject) => {
      login({
        username: getUSERNAME_KEY(),
        password: getPASSWORD_KEY()
      }).then((res) => {
        console.log(res)
        const routes = []
        const obj = res.data.router
        for (var i = 0; i < obj.length; i++) {
          if (obj[i].childrenList == null) {
            routes.push({
              sort: obj[i].sort,
              path: obj[i].path,
              redirect: obj[i].name,
              component: Layout,
              meta: JSON.parse(obj[i].meta),
              children: [{
                id: obj[i].sort,
                path: 'index',
                name: obj[i].name,
                component: views[obj[i].name],
                meta: JSON.parse(obj[i].meta),
              }]
            })
          } else {
            let value = {
              sort: obj[i].sort,
              path: obj[i].path,
              redirect: obj[i].childrenList[0].name,
              component: Layout,
              meta: JSON.parse(obj[i].meta),
              children: []
            }
            for (var j = 0; j < obj[i].childrenList.length; j++) {
              value.children.push({
                path: obj[i].childrenList[j].path,
                name: obj[i].childrenList[j].name,
                sort: obj[i].childrenList[j].sort,
                component: views[obj[i].childrenList[j].component],
                meta: JSON.parse(obj[i].childrenList[j].meta)
              })
            }
            routes.push(value)
          }
        }
        console.log(routes)
        resolve(routes)
        commit('SET_USSER_ROUTES', routes)
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
